import React, {useEffect, useState} from 'react';
import {useDispatch, useSelector} from "react-redux";
import {getTypeList, setBookTypeId} from "../store/modules/typeStore";
import {Tag} from "antd";
import {useLocation} from "react-router-dom";
import {setIssueTypeId} from "../store/modules/typeStore";
/**
 * 分类组件
 * @param props
 * @returns {Element}
 * @constructor
 */
function TypeSelect(props) {
    const {typeList} = useSelector(state => state.type)
    const dispatch = useDispatch()
    const [tagList, setTagList] = useState([])
    const location = useLocation();
    const changeType = (typeId) => {
        if (location.pathname === '/issues') {
            // 处于问答页面
            dispatch(setIssueTypeId(typeId))
        } else if (location.pathname === '/books') {
            // 处于书籍页面
            dispatch(setBookTypeId(typeId))
        }
    }
    useEffect(() => {
        if (!typeList.length) {
            dispatch(getTypeList())
        }
        // 需要使用临时变量 arr 来存储一下tag（每次依赖更新获取，赋值后arr 销毁），然后再赋值给 tagList，否则tagList会一直增加
        let arr = []
        if (typeList.length) {
            arr.push(
                <Tag
                    color="magenta"
                    value="all"
                    key="all"
                    style={{cursor: 'pointer'}}
                    onClick={()=>changeType('all')}
                >全部</Tag>
            )
            typeList.forEach(item => {
                arr.push(
                    <Tag
                        color="blue"
                        value={item._id}
                        key={item._id}
                        style={{cursor: 'pointer'}}
                        onClick={()=>changeType(item._id)}
                    >
                        {item.typeName}
                    </Tag>
                )
            })
        }
        setTagList(arr)
    }, [typeList]);
    return (
        <div>{tagList}</div>
    );
}

export default TypeSelect;